package com.ioftv.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ioftv.common.Result;
import com.ioftv.dto.ImportResultDTO;
import com.ioftv.dto.PageResult;
import com.ioftv.dto.ProjectPackageExcelDTO;
import com.ioftv.entity.ProjectPackage;
import com.ioftv.listener.ProjectPackageImportListener;
import com.ioftv.service.ProjectPackageService;
import com.ioftv.util.UserContextUtil;
import com.ioftv.util.RolePermissionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 项目总览管理Controller
 * 实现项目包量统计的增删改查、分页查询、Excel导入导出等功能
 */
@Slf4j
@RestController
@RequestMapping("/admin/project-overview")
public class ProjectPackageController {

    @Autowired
    private ProjectPackageService projectPackageService;

    /**
     * 3.1 分页查询项目总览列表
     * GET /admin/project-overview
     */
    @GetMapping
    public Result<PageResult<ProjectPackage>> getPageList(
            @RequestParam Integer currentPage,
            @RequestParam Integer pageSize,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
            HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 创建分页对象
        Page<ProjectPackage> page = new Page<>(currentPage, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<ProjectPackage> queryWrapper = new LambdaQueryWrapper<>();
        if (startDate != null) {
            queryWrapper.ge(ProjectPackage::getStatDate, startDate);
        }
        if (endDate != null) {
            queryWrapper.le(ProjectPackage::getStatDate, endDate);
        }
        
        // 管理员可以查看所有数据，普通用户只能查看自己的数据
        if (!RolePermissionUtil.ROLE_ADMIN.equals(role)) {
            queryWrapper.eq(ProjectPackage::getUserId, userId);
        }
        
        queryWrapper.orderByDesc(ProjectPackage::getStatDate);
        
        // 执行分页查询
        Page<ProjectPackage> resultPage = projectPackageService.page(page, queryWrapper);
        
        // 构造返回结果
        PageResult<ProjectPackage> pageResult = new PageResult<>(
            resultPage.getRecords(),
            resultPage.getTotal(),
            currentPage,
            pageSize
        );
        
        return Result.success(pageResult);
    }

    /**
     * 3.2 新增项目总览
     * POST /admin/project-overview
     */
    @PostMapping
    public Result<ProjectPackage> addProjectPackage(@RequestBody ProjectPackage projectPackage, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 检查日期是否已存在（仅检查当前用户的数据）
        LambdaQueryWrapper<ProjectPackage> checkWrapper = new LambdaQueryWrapper<>();
        checkWrapper.eq(ProjectPackage::getStatDate, projectPackage.getStatDate());
        if (!RolePermissionUtil.ROLE_ADMIN.equals(role)) {
            checkWrapper.eq(ProjectPackage::getUserId, userId);
        }
        ProjectPackage existing = projectPackageService.getOne(checkWrapper);
        
        if (existing != null) {
            return Result.error(1001, "该日期已存在统计数据");
        }
        
        // 设置用户ID
        projectPackage.setUserId(userId);
        
        // 保存数据
        boolean success = projectPackageService.save(projectPackage);
        if (success) {
            return Result.success(projectPackage);
        } else {
            return Result.error("新增失败");
        }
    }

    /**
     * 3.3 修改项目总览
     * PUT /admin/project-overview/{id}
     */
    @PutMapping("/{id}")
    public Result<ProjectPackage> updateProjectPackage(@PathVariable Long id, @RequestBody ProjectPackage projectPackage, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 构建查询条件
        LambdaQueryWrapper<ProjectPackage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectPackage::getId, id);
        // 管理员可以修改所有数据，普通用户只能修改自己的数据
        if (!RolePermissionUtil.ROLE_ADMIN.equals(role)) {
            queryWrapper.eq(ProjectPackage::getUserId, userId);
        }
        
        // 检查数据是否存在
        ProjectPackage existing = projectPackageService.getOne(queryWrapper);
        if (existing == null) {
            return Result.error(404, "数据不存在或无权限修改");
        }
        
        // 设置ID
        projectPackage.setId(id);
        
        // 保持原有的用户ID
        projectPackage.setUserId(existing.getUserId());
        
        // 更新数据
        boolean success = projectPackageService.updateById(projectPackage);
        if (success) {
            // 重新查询返回最新数据
            ProjectPackage updated = projectPackageService.getById(id);
            return Result.success(updated);
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 3.4 删除项目总览
     * DELETE /admin/project-overview/{id}
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteProjectPackage(@PathVariable Long id, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        // 构建查询条件
        LambdaQueryWrapper<ProjectPackage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProjectPackage::getId, id);
        // 管理员可以删除所有数据，普通用户只能删除自己的数据
        if (!RolePermissionUtil.ROLE_ADMIN.equals(role)) {
            queryWrapper.eq(ProjectPackage::getUserId, userId);
        }
        
        // 检查数据是否存在
        ProjectPackage existing = projectPackageService.getOne(queryWrapper);
        if (existing == null) {
            return Result.error(404, "数据不存在或无权限删除");
        }
        
        // 删除数据
        boolean success = projectPackageService.removeById(id);
        if (success) {
            return Result.success(null);
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 3.5 下载Excel导入模板
     * GET /admin/project-overview/template
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        try {
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("项目总览导入模板", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 创建空模板（只有表头）
            List<ProjectPackageExcelDTO> templateData = new ArrayList<>();

            // 写入Excel（只生成表头，不含数据）
            EasyExcel.write(response.getOutputStream(), ProjectPackageExcelDTO.class)
                    .sheet("项目总览数据")
                    .doWrite(templateData);

            log.info("下载Excel模板成功");
        } catch (IOException e) {
            log.error("下载Excel模板失败", e);
            throw new RuntimeException("下载模板失败: " + e.getMessage());
        }
    }

    /**
     * 3.6 批量导入Excel数据
     * POST /admin/project-overview/import
     */
    @PostMapping("/import")
    public Result<ImportResultDTO> importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        // 获取当前用户信息
        Long userId = UserContextUtil.getCurrentUserId(request);
        String username = UserContextUtil.getCurrentUsername(request);
        String role = UserContextUtil.getCurrentUserRole(request);
        
        if (file == null || file.isEmpty()) {
            return Result.error("请选择要导入的文件");
        }

        String fileName = file.getOriginalFilename();
        if (fileName == null || (!fileName.endsWith(".xlsx") && !fileName.endsWith(".xls"))) {
            return Result.error("仅支持Excel文件格式（.xlsx或.xls）");
        }

        try {
            log.info("开始导入Excel文件: {}", fileName);

            // 创建导入结果对象
            ImportResultDTO importResult = new ImportResultDTO();

            // 使用监听器模式读取Excel，支持大文件
            ProjectPackageImportListener listener = new ProjectPackageImportListener(projectPackageService, importResult);
            listener.setUserId(userId); // 设置用户ID，用于导入时关联数据
            
            EasyExcel.read(file.getInputStream(), 
                          ProjectPackageExcelDTO.class, 
                          listener)
                    .sheet()
                    .doRead();

            log.info("导入完成: 总行数={}, 成功={}, 失败={}", 
                    importResult.getTotalRows(), 
                    importResult.getSuccessRows(), 
                    importResult.getFailRows());

            return Result.success(importResult);

        } catch (IOException e) {
            log.error("导入Excel文件失败", e);
            return Result.error("导入失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("导入Excel文件异常", e);
            return Result.error("导入异常: " + e.getMessage());
        }
    }
}